package com.caiyigo.baihua.controller;

import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.caiyigo.baihua.Const.Const;
import com.caiyigo.baihua.Const.UrlConfig;
import com.caiyigo.baihua.model.SystemUser;
import com.caiyigo.baihua.service.UserService;
import com.caiyigo.baihua.utils.RSA;
import com.caiyigo.baihua.utils.Sec;

@Controller
public class IndexController extends BaseController {
	@Autowired
	UserService userService;

	/**
	 * 返回登陆视图
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginView", method = RequestMethod.GET)
	public String loginView(HttpServletRequest request) {
		RSAPublicKey publicKey = RSA.getDefaultPublicKey();
		String modulus = new String(Hex.encodeHex(publicKey.getModulus()
				.toByteArray()));
		String exponent = new String(Hex.encodeHex(publicKey
				.getPublicExponent().toByteArray()));
		request.setAttribute("modulus", modulus);
		request.setAttribute("exponent", exponent);
		return UrlConfig.COMMON.LOGIN;
	}

	/**
	 * 跳转到登陆页面
	 * 
	 * @return
	 */
	// @RequestMapping(value = { "/{jump:jump;?.*}" }, method =
	// RequestMethod.GET)
	// public String jump() {
	// return "page/common/jump";
	// }
	@RequestMapping(value = { "/jump" }, method = RequestMethod.GET)
	public String jump() {
		return UrlConfig.COMMON.JUMP;
	}

	// @RequestMapping(value = { "/{url:mvc/*}" }, method = RequestMethod.GET)
	// public void to(@PathVariable String url) {
	// System.out.println(url);
	// //
	// //return "page/common/jump";
	// }
	// http://localhost:8080/zooweb/jump;jsessionid=52FE66D33D52B21BA81EEDE2768DD12F
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		return UrlConfig.INDEX.INDEX;
	}

	/**
	 * 登陆处理
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(
			@RequestParam(value = "key", required = true) String key,
			HttpServletRequest request, RedirectAttributes attr) {
		String[] result = RSA.decryptUsernameAndPwd(key);
		Map<String, String> messages = new HashMap<String, String>();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(result[0],
					Sec.md5(result[1]));
			Subject subject = SecurityUtils.getSubject();
			if (!subject.isAuthenticated()) {
				token.setRememberMe(true);
				subject.login(token);

				subject.getSession(true).setAttribute(Const.SESSION_USER,
						userService.selectByName(result[0]));

			}

			return RedirectAction("/index");

		} catch (UnknownAccountException e) {

			messages.put("msg", "用户名不存在");
			return RedirectAction(attr, messages, "/loginView");

		} catch (IncorrectCredentialsException e) {

			messages.put("msg", "密码错误");
			return RedirectAction(attr, messages, "/loginView");

		} catch (LockedAccountException e) {
			messages.put("msg", "对不起 帐号被封了");
			return RedirectAction(attr, messages, "/loginView");

		} catch (ExcessiveAttemptsException e) {

			messages.put("msg", "尝试次数过多 请明天再试");
			return RedirectAction(attr, messages, "/loginView");
		} catch (AuthenticationException e) {
			messages.put("msg", "对不起 没有权限 访问");
			return RedirectAction(attr, messages, "/loginView");

		} catch (Exception e) {
			messages.put("msg", "请重新登录");
			return RedirectAction(attr, messages, "/loginView");

		}

	}

	@RequestMapping(value = "/loginOut", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void loginOut(HttpServletRequest request,
			HttpServletResponse response) {

		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		renderHtml(response,
				"<html><script> window.open('" + request.getContextPath()
						+ UrlConfig.LOGIN + "','_top') </script></html>");

	}

	@RequestMapping(value = "/system/role", method = RequestMethod.GET)
	public String ToRolePage() {
		return UrlConfig.SYSTEM.ROLE;
	}

	@RequestMapping(value = "/system/user", method = RequestMethod.GET)
	public String ToUserPage() {
		return UrlConfig.SYSTEM.USER;
	}

	@RequestMapping(value = "/system/log", method = RequestMethod.GET)
	public String ToLogPage() {
		return UrlConfig.SYSTEM.LOG;
	}

	@RequestMapping(value = "/business/xuesheng", method = RequestMethod.GET)
	public String ToXueshengPage() {
		return UrlConfig.BUSINESS.XUESHENG;
	}

	@RequestMapping(value = "/business/kaoshizw", method = RequestMethod.GET)
	public String ToKaoshizwPage() {
		return UrlConfig.BUSINESS.KAOSHIZW;
	}

	@RequestMapping(value = "/business/kaoshicj", method = RequestMethod.GET)
	public String ToKaoshicjPage() {
		return UrlConfig.BUSINESS.KAOSHICJ;
	}

	@RequestMapping(value = "/business/zhuanye", method = RequestMethod.GET)
	public String ToZhuanyePage() {
		return UrlConfig.BUSINESS.ZHUANYE;
	}



	@RequestMapping(value = "/business/zykm", method = RequestMethod.GET)
	public String ToZykmPage() {
		return UrlConfig.BUSINESS.ZYKM;
	}


	@RequestMapping(value = "/business/kaoshikemu", method = RequestMethod.GET)
	public String ToKaoshikemuPage() {
		return UrlConfig.BUSINESS.KAOSHIKEMU;
	}


	

}
